package lg.minecraft.plugin.entityclear.task;

import lg.minecraft.plugin.entityclear.LGEntityClear;
import lg.minecraft.plugin.entityclear.manager.EntityTaskManager;
import lg.minecraft.plugin.library.task.BaseTask;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;

/**
 * @author langle__
 * @version 1.0
 */
public class EntityClearTaskExecutor extends BaseTask {

    public static final EntityClearTaskExecutor INSTANCE = new EntityClearTaskExecutor(LGEntityClear.getInstance(), 1);

    private final JavaPlugin plugin;
    private final int interval;

    public EntityClearTaskExecutor(JavaPlugin plugin, int interval) {
        this.plugin = plugin;
        this.interval = interval;
    }

    @Override
    public void run() {
        for (EntityClearTask task : EntityTaskManager.INSTANCE.getValues()) {
            int secondsLeft = (int) (task.getTimeLeft() / 1000);
            String message = task.getMessage(secondsLeft, true);
            if (message != null) Bukkit.broadcastMessage(message);
            if (!task.shouldClear()) continue;
            task.reset();
            long start = System.currentTimeMillis();
            int count = task.clearEntities();
            long end = System.currentTimeMillis();
            long executionTime = end - start;
            String clearMessage = task.getTemplate().getClearMessage();
            if (clearMessage != null) {
                String tempMessage = clearMessage
                        .replace("{count}", String.valueOf(count))
                        .replace("{executionTime}", String.valueOf(executionTime));
                Bukkit.broadcastMessage(tempMessage);
            }
        }
    }

    public void start() {
        this.runTaskTimer(plugin, interval, interval);
    }

}
